package com.nsy.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nsy.shortlink.admin.common.convention.exception.ClientException;
import com.nsy.shortlink.admin.common.enums.UserErrorCodeEnum;
import com.nsy.shortlink.admin.dao.entity.UserDO;
import com.nsy.shortlink.admin.dao.mapper.UserMapper;
import com.nsy.shortlink.admin.dto.req.UserLoginReqDTO;
import com.nsy.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.nsy.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.nsy.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.nsy.shortlink.admin.dto.resp.UserRespDTO;
import com.nsy.shortlink.admin.service.GroupService;
import com.nsy.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.User;
import org.apache.catalina.connector.ClientAbortException;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLocalCachedMap;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

import static com.nsy.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.nsy.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static com.nsy.shortlink.admin.common.enums.UserErrorCodeEnum.USER_NAME_EXIST;
import static com.nsy.shortlink.admin.common.enums.UserErrorCodeEnum.USER_SAVE_ERROR;

/**
 * @className: UserServiceImpl
 * @author: 宁舒意
 * @description: TODO
 * @date: 2024/9/25 19:48
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    private final RedissonClient redissonClient;

    private final StringRedisTemplate stringRedisTemplate;

    private final GroupService groupService;
    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> eq = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, username);
        UserDO userDO = this.getOne(eq);
        UserRespDTO result =new UserRespDTO();
        if(userDO==null)
            return null;
        else {
            BeanUtils.copyProperties(userDO,result);
            return result;
        }

    }


    @Override
    public boolean hasUsername(String username) {
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(UserRegisterReqDTO param) {
        if(hasUsername(param.getUsername())){
            throw new ClientException(USER_NAME_EXIST);
        }
        RLock lock =redissonClient.getLock(LOCK_USER_REGISTER_KEY+param.getUsername());
        if(!lock.tryLock()){
            throw new ClientException(USER_NAME_EXIST);
        }

        try {
                UserDO userDo = BeanUtil.toBean(param, UserDO.class);
                int insert = baseMapper.insert(userDo);
                if (insert < 1) {
                    throw new ClientException(USER_SAVE_ERROR);
                }
                //这里如果错误了就回滚了，数据库和布隆过滤器都不会有这个分组
            groupService.saveGroup(param.getUsername(), "默认分组");
            userRegisterCachePenetrationBloomFilter.add(param.getUsername());
        }catch (DuplicateKeyException e){
            throw new ClientException(USER_NAME_EXIST);
        }
        finally {
            lock.unlock();
        }




    }

    @Override
    public void update(UserUpdateReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> eq = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, requestParam.getUsername());
        UserDO userDO =BeanUtil.toBean(requestParam,UserDO.class);
        baseMapper.update(userDO,eq);
    }


    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0);
        //首先查询到用户
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException("用户不存在");
        }
        //根据用户名在Redis中查询用户信息
        Map<Object, Object> hasLoginMap = stringRedisTemplate.opsForHash().entries(USER_LOGIN_KEY + requestParam.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            //延长token时间
            stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), 30L, TimeUnit.DAYS);
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            //返回token
            return new UserLoginRespDTO(token);
        }
        /**
         * Hash
         * Key：login_用户名
         * Value：
         *  Key：token标识
         *  Val：JSON 字符串（用户信息）
         */
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put(USER_LOGIN_KEY + requestParam.getUsername(), uuid, JSON.toJSONString(userDO));
        stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), 30L, TimeUnit.MINUTES);
        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token) != null;
    }

    @Override
    public void logout(String username, String token) {
        if (checkLogin(username, token)) {
            stringRedisTemplate.delete(USER_LOGIN_KEY + username);
            return;
        }
        throw new ClientException("用户Token不存在或用户未登录");
    }
}
